package org.corey.share.db.service;

import org.corey.share.db.dao.UserDao;
import org.corey.share.db.entity.User;
import org.corey.share.db.manager.DefaultDaoFactory;
import org.corey.share.db.manager.EM;
import org.corey.share.misc.Common;
import org.corey.share.misc.UnValidationMsg;
import org.corey.share.throwable.ValidationUserException;

public class UserServiceImpl implements UserService {

	private UserDao dao = new DefaultDaoFactory().createUserDao();
	private static UserService instance = new UserServiceImpl();

	public static UserService getInstance() {
		return instance;
	}

	public boolean rePassword(String userName, String oldPassword,
			String newPassword) throws ValidationUserException {
		EM.beginTransaction();
		User user = this.validUser(userName, oldPassword);
		user.setPassword(newPassword);
		boolean result = dao.updateUser(user);
		EM.commitTransaction();
		return result;
	}

	public User validUser(String userName, String password)
			throws ValidationUserException {
		User user = dao.getUserByName(userName);
		if (user == null) {
			throw new ValidationUserException("login failure",
					UnValidationMsg.NOUSER);
		}
		if (Common.isEmpty(password)) {
			throw new ValidationUserException("login failure",
					UnValidationMsg.PASSWORD_EMPTY);
		}
		if (!password.equals(user.getPassword())) {
			throw new ValidationUserException("login failure",
					UnValidationMsg.PASSWORD_ERROR);
		}
		return user;
	}

	public User registeUser(User user) {
		EM.beginTransaction();
		boolean result = dao.addUser(user);
		EM.commitTransaction();
		if (result) {
			return user;
		}
		return null;
	}

	@Override
	public User getUser(String userName) {
		return dao.getUserByName(userName);
	}
}
